package com.android.juguotang.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.juguotang.SearchActivity;
import com.android.juguotang.activity.BaseObject;
import com.android.juguotang.activity.mine.LoginActivity;
import com.android.juguotang.fragment.group.Fragment_Group;
import com.android.juguotang.fragment.group.Fragment_serch;
import com.android.juguotang.fragment.member.Fragment_SeaAmoy;
import com.android.juguotang.model.group.MainGoodsCatDataCallback;
import com.android.juguotang.R;
import com.android.juguotang.fragment.group.Fragment_TabSearchList;
import com.android.juguotang.model.group.MainGoodsCatData;
import com.android.juguotang.model.member.MemberInfoData;
import com.android.juguotang.model.member.MemberInfoDataCallback;
import com.android.juguotang.utils.ConstantsUrl;
import com.android.juguotang.utils.HttpUtils;
import com.android.juguotang.utils.LoginState;
import com.android.juguotang.utils.MyLog;
import com.android.juguotang.utils.ObjectUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * App首页
 */

public class Fragment1 extends Fragment {


    @BindView(R.id.tab)
    TabLayout tabLayout;
    @BindView(R.id.pager)
    ViewPager viewPager;
//    @BindView(R.id.main_top_title)
//    TextView mainTopTitle;
//    @BindView(R.id.main_top_bg)
//    Toolbar mainTopBg;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.imageView2)
    ImageView imageView2;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.num_msg)
    TextView num_msg;
    @BindView(R.id.framelayout)
    FrameLayout framelayout;
    @BindView(R.id.user_ll)
    RelativeLayout user_ll;
    @BindView(R.id.main_top_citychoose)
    TextView main_top_citychoose;


    private View view;
    private FragmentActivity mcontext;
    private boolean networkConnected;
    public static Fragment1 fragment1;
    private ImageView sort_list_listorder_iv;
    private ImageView sort_list_sales_iv;
    private ImageView sort_list_price_iv;
    //private DiskLruCacheHelper helper;
    public Fragment1() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        String appName = getResources().getString(R.string.app_name);
//        mainTopTitle.setText(appName);
//        mainTopTitle.setTextColor(Color.parseColor("#ffffff"));
//        mainTopBg.setBackgroundColor(Color.parseColor("#FF2741"));
        fragment1 = Fragment1.this;
        GetSortData();
        GetDataNumber();
        return view;
    }

    private void initUI() {

        GroupFragmentPagerAdapter pagerAdapter = new GroupFragmentPagerAdapter(mcontext.getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab == null) return;
            //这里使用到反射，拿到Tab对象后获取Class
            Class c = tab.getClass();
            try {
                //Filed “字段、属性”的意思,c.getDeclaredField 获取私有属性。
                //"mView"是Tab的私有属性名称(可查看TabLayout源码),类型是 TabView,TabLayout私有内部类。
                Field field = c.getDeclaredField("mView");
                //值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。
                //如果不这样会报如下错误
                // java.lang.IllegalAccessException:
                //Class com.test.accessible.Main
                //can not access
                //a member of class com.test.accessible.AccessibleTest
                //with modifiers "private"
                field.setAccessible(true);
                final View view = (View) field.get(tab);
                if (view == null) return;
                view.setTag(i);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) view.getTag();
                        //这里就可以根据业务需求处理点击事件了。
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        imageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setVisibility(View.GONE);
                framelayout.setVisibility(View.VISIBLE);
               String record= et_search.getText().toString();

                 Fragment   Fragment3 = Fragment_serch.newInstance(record);
                FragmentManager manager = getActivity().getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.framelayout, Fragment3, "");
                transaction.commit();
            }
        });
        user_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("我的消息", 0);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
            }
        });
        main_top_citychoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mcontext, BaseObject.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "同城");
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, id);
//                intent.putExtra(ConstantsUrl.INTENT_KEY.RETURN_TYPE, return_type);
                startActivity(intent);
            }
        });
    }
    private void ToObject(String title, int type) {
        Intent intent_q = new Intent(getActivity(), BaseObject.class);
        intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, title);
        switch (type) {
            case 0:
                break;
            case 1:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, ConstantsUrl.baseDomain + "content/index/22");
                break;
            case 2:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, ConstantsUrl.baseDomain + "content/index/23");
                break;
            case 3:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, commission);
                break;
        }
        startActivity(intent_q);
    }
    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        GetSortData();
    }

    private class GroupFragmentPagerAdapter extends FragmentPagerAdapter {


        public GroupFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                viewPager.setVisibility(View.VISIBLE);
                framelayout.setVisibility(View.GONE);
                return Fragment_Group.newInstance();

            } else {
                viewPager.setVisibility(View.VISIBLE);
                framelayout.setVisibility(View.GONE);
                return Fragment_TabSearchList.newInstance(true, mListSort.get(position).getId(), mListSort.get(position).getCatname());
            }
        }

        @Override
        public int getCount() {
            return mListSort.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mListSort.get(position).getCatname();
        }
    }

    /**
     * 商品分类列表
     */
    private List<MainGoodsCatData.DataBean.Cat_ListBean> mListSort = new ArrayList<>();

    private void GetSortData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.SORTLISTDATA_TWO;
            MyLog.e("地址", address);
            HttpUtils.get(address, null, new MainGoodsCatDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainGoodsCatData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        mListSort.clear();
                        MainGoodsCatData.DataBean data = response.getData();
                        mListSort.add(new MainGoodsCatData.DataBean.Cat_ListBean("", "首页"));
                        if (data != null && ObjectUtils.listHasData(data.getCat_list())) {
                            List<MainGoodsCatData.DataBean.Cat_ListBean> catListBeen = data.getCat_list();
                            mListSort.addAll(catListBeen);
                        }
                        initUI();
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "连接连接出现异常");
        }
    }

    public static Fragment1 getInstent(){
        return fragment1;
    }

    public void setViewPager(String sortID){
        for(int i = 0; i < mListSort.size(); i++){
            MainGoodsCatData.DataBean.Cat_ListBean cat_listBean = mListSort.get(i);
            if(cat_listBean!=null) {
                if (sortID.equals(cat_listBean.getId())) {
                    viewPager.setCurrentItem(i);
                }
            }
        }
    }

    private String commission;
    private void GetDataNumber() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDINGDANGNUM;
            MyLog.e("地址", address);
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new MemberInfoDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MemberInfoData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    MemberInfoData.DataBean data = response.getData();
                    if (response.getCode() == 0 && data != null) {
                        commission = data.getCommission();
                        //消息数量
                        String msgUnreadCount = data.getMsgUnreadCount();
                        if (msgUnreadCount != null && msgUnreadCount.equals("0")) {
                            num_msg.setVisibility(View.INVISIBLE);
                        } else {
                            num_msg.setVisibility(View.VISIBLE);
                            num_msg.setText(msgUnreadCount + "");
                        }


                    } else {
//                        noData.setVisibility(View.VISIBLE);
//                        noDataTv.setText(response.getMsg());
//                        noDataTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }
}



